// hotel-management-frontend/src/client/History.js

import React, { useState, useEffect } from "react"; // useEffect is correctly imported now
import { Card, Form, Input, Button, Table, message, Tag } from "antd"; // Tag is correctly imported now, Descriptions removed
import { UserOutlined } from "@ant-design/icons";
import { clientAPI } from "../services/api";
import moment from "moment";

// Helper component for expanding consumption details in history table
const ExpandedConsumptionRow = ({ checkinId }) => {
  const [consumptions, setConsumptions] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchConsumptions = async () => {
      setLoading(true);
      try {
        // Client API for consumption details by checkin ID
        const { data } = await clientAPI.getConsumptionsByCheckinId(checkinId);
        setConsumptions(data);
      } catch (error) {
        console.error("获取消费详情失败:", error);
        message.error("获取消费详情失败");
      } finally {
        setLoading(false);
      }
    };

    fetchConsumptions();
  }, [checkinId]); // Dependency on checkinId

  const consumptionColumns = [
    { title: "商品名称", dataIndex: "item_name", key: "item_name" },
    { title: "数量", dataIndex: "quantity", key: "quantity" },
    {
      title: "单价 (¥)",
      dataIndex: "unit_price",
      key: "unit_price",
      render: (price) => `¥${parseFloat(price || 0).toFixed(2)}`,
    },
    {
      title: "总金额 (¥)",
      dataIndex: "amount",
      key: "amount",
      render: (amount) => `¥${parseFloat(amount).toFixed(2)}`,
    },
    {
      title: "消费时间",
      dataIndex: "consume_time",
      key: "consume_time",
      render: (text) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
    },
  ];

  return (
    <div
      style={{
        margin: "10px 0",
        padding: "10px",
        background: "#f5f5f5",
        borderRadius: "4px",
      }}
    >
      <h4>消费明细</h4>
      <Table
        columns={consumptionColumns}
        dataSource={consumptions}
        rowKey="consumption_id"
        pagination={false}
        loading={loading}
        size="small"
        variant="bordered"
        locale={{ emptyText: "无消费记录" }}
      />
    </div>
  );
};

const ClientHistory = () => {
  const [form] = Form.useForm();
  const [checkins, setCheckins] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleQuery = async (values) => {
    if (!values.idCard) {
      message.warning("请输入身份证号");
      return;
    }
    setLoading(true);
    setCheckins([]);
    setError(null);
    try {
      const response = await clientAPI.getCheckinsByGuestCard(values.idCard);
      setCheckins(response.data);
      if (response.data.length === 0) {
        message.info("未找到入住记录");
      } else {
        message.success(`已找到 ${response.data.length} 条入住记录`);
      }
    } catch (err) {
      console.error("查询入住记录失败:", err);
      setError(
        "查询入住记录失败: " + (err.response?.data?.message || err.message)
      );
      message.error("查询入住记录失败");
    } finally {
      setLoading(false);
    }
  };

  const checkinColumns = [
    { title: "房间号", dataIndex: "room_number", key: "room_number" },
    { title: "房间类型", dataIndex: "room_type", key: "room_type" },
    {
      title: "房间单价 (¥/天)",
      dataIndex: "room_price",
      key: "room_price",
      render: (price) => `¥${parseFloat(price).toFixed(2)}`,
    },
    {
      title: "入住时间",
      dataIndex: "checkin_date",
      key: "checkin_date",
      render: (text) => moment(text).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "退房时间",
      dataIndex: "checkout_date",
      key: "checkout_date",
      render: (text) =>
        text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : "未退房",
    },
    {
      title: "总金额 (¥)",
      dataIndex: "total_amount",
      key: "total_amount",
      render: (amount) =>
        amount ? `¥${parseFloat(amount).toFixed(2)}` : "N/A",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        let color = "";
        if (status === "入住中") color = "blue";
        else if (status === "已退房") color = "green";
        return <Tag color={color}>{status}</Tag>;
      },
    },
  ];

  return (
    <Card
      title="我的入住及消费历史"
      style={{ maxWidth: 1200, margin: "20px auto" }}
      variant="bordered"
    >
      <Form
        form={form}
        name="history_query"
        layout="inline"
        onFinish={handleQuery}
        style={{ marginBottom: 24 }}
      >
        <Form.Item
          name="idCard"
          label="身份证号"
          rules={[
            { required: true, message: "请输入身份证号" },
            { len: 18, message: "身份证号应为18位" },
          ]}
        >
          <Input
            placeholder="请输入身份证号"
            prefix={<UserOutlined />}
            style={{ width: 300 }}
            onPressEnter={() => form.submit()}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            查询
          </Button>
        </Form.Item>
      </Form>

      {error && <div style={{ color: "red", marginBottom: 20 }}>{error}</div>}

      {checkins.length > 0 ? (
        <Table
          columns={checkinColumns}
          dataSource={checkins}
          rowKey="checkin_id"
          pagination={{ pageSize: 5 }}
          loading={loading}
          variant="bordered"
          expandable={{
            expandedRowRender: (record) => (
              <ExpandedConsumptionRow checkinId={record.checkin_id} />
            ),
            rowExpandable: (record) => record.checkin_id !== null,
          }}
          locale={{ emptyText: "无入住记录" }}
        />
      ) : (
        !loading &&
        !error && (
          <div style={{ textAlign: "center", color: "#888" }}>
            请输入身份证号并点击查询，查看您的入住和消费记录。
          </div>
        )
      )}
    </Card>
  );
};

export default ClientHistory;
